package ar.uba.fi.tonyvaliente.web.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ar.uba.fi.tonyvaliente.web.manager.DocumentAddManager;

/**
 * Servlet implementation class for Servlet: DocumentAdd
 *
 */
 public class DocumentAdd extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   private static Log log = LogFactory.getLog(DocumentAdd.class);
   
	public DocumentAdd() {
		super();
	}   	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}  	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String path = request.getParameter("path");
		log.info("AddDocument: " + path);
		
		String message;
		boolean success;
		
		if(path != null && !path.isEmpty()){
			String indexType = request.getParameter("indexType");
			
			if(indexType != null){
				DocumentAddManager addManager = new DocumentAddManager();
				success = addManager.addDocument(path, indexType);
				message = addManager.getMessage();
			}else{
				message = "The index type is mandatory.";
				success = false;
			}
		}else{
			message = "The document path is mandatory.";
			success = false;
		}
		
		request.setAttribute("success", success);
		request.setAttribute("message", message);
		
        RequestDispatcher dispatcher = request.getRequestDispatcher("addDocument.jsp");
        dispatcher.forward(request, response);
		
	}
	
}